package com.xscr.api.service.forum;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resources;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;

import com.rop.annotation.HttpAction;
import com.rop.annotation.IgnoreSignType;
import com.rop.annotation.NeedInSessionType;
import com.rop.annotation.ServiceMethod;
import com.rop.annotation.ServiceMethodBean;
import com.rop.response.Response;
import com.xscr.api.pojo.CommunityDTO;
import com.xscr.api.pojo.ImageDTO;
import com.xscr.api.pojo.OrderDTO;
import com.xscr.api.pojo.ReplyDTO;
import com.xscr.api.pojo.TopicDTO;
import com.xscr.api.pojo.UserDTO;
import com.xscr.api.request.GetCommunityRequest;
import com.xscr.api.request.GetOrderRequest;
import com.xscr.api.request.GetTopicDetailRequest;
import com.xscr.api.request.GetTopicListRequest;
import com.xscr.api.request.LoginRequest;
import com.xscr.api.request.PostReplyRequest;
import com.xscr.api.request.RewardTopicRequest;
import com.xscr.api.request.UploadUserPhotoRequest;
import com.xscr.forum.po.ForumCircle;
import com.xscr.forum.po.ForumImage;
import com.xscr.forum.po.ForumReply;
import com.xscr.forum.po.ForumTopic;
import com.xscr.forum.service.ForumCircleService;
import com.xscr.forum.service.ForumImageService;
import com.xscr.forum.service.ForumReplyService;
import com.xscr.forum.service.ForumTopicService;
import com.xscr.mybatis.utility.PageBean;
import com.xscr.user.po.User;
import com.xscr.user.service.UserService;

@ServiceMethodBean(version = "1.0", ignoreSign = IgnoreSignType.NO)
public class ForumAction {
	
	private static final Logger logger=LoggerFactory.getLogger(ForumAction.class);

	@Autowired
	private ForumCircleService forumCircleService;

	@Autowired
	private ForumTopicService forumTopicService;

	@Autowired
	private ForumReplyService forumReplyService;

	@Autowired
	private UserService userService;

	@Autowired
	private ForumImageService forumImageService;

	/**
	 * 获取圈子列表
	 * 
	 * @param getCommunityRequest
	 * @return
	 */
	@ServiceMethod(method = "forum.getCommunityList", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.GET)
	public Response getCommunityList(GetCommunityRequest getCommunityRequest) {
		Response response = new Response();
		String msg = "";

		ForumCircle forumCircle = new ForumCircle();
		forumCircle.setStatus(1);

		PageBean<ForumCircle> pageBean = new PageBean<ForumCircle>();

		pageBean.setSortFields("create_time");
		pageBean.setOrder("ASC");
		pageBean.setParameter(forumCircle);

		try {
			pageBean = forumCircleService.findForumCircleByConditions(pageBean);
			List<ForumCircle> forumList = pageBean.getResult();

			Map<String, Object> data = new HashMap<String, Object>(5);

			List<CommunityDTO> communityList = new ArrayList<CommunityDTO>();
			if (forumList != null && forumList.size() > 0) {
				for (ForumCircle forum : forumList) {
					CommunityDTO community = new CommunityDTO();
					community.setCommunityId(forum.getCircleId());
					community.setDescription(forum.getContent());
					community.setImgUrl(forum.getIcon());
					community.setName(forum.getTitle());
					communityList.add(community);
				}
			}
			else
			{
				response.getResult().setResult("0");
				response.getResult().setMessage("圈子列表为空");
				return response;			
			}
			data.put("communityList", communityList);

			response.setData(data);
		} catch (Exception e) {
			logger.error("getCommunityList error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("获取圈子列表错误");
			return response;
		}
		response.getResult().setResult("1");
		response.getResult().setMessage("获取圈子列表成功");
		return response;
	}

	/**
	 * 获取帖子列表
	 * 
	 * @param getTopicListRequest
	 * @return
	 */
	@ServiceMethod(method = "forum.getTopicListByCommunityId", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.GET)
	public Response getTopicListByCommunityId(
			GetTopicListRequest getTopicListRequest) {
		Response response = new Response();
		String msg = "";
		Integer circleId = getTopicListRequest.getCommunityId();
		Integer page = getTopicListRequest.getPageCount();
		Integer type = getTopicListRequest.getType();
		
		if(circleId==null||StringUtils.isBlank(circleId.toString())||page==null)
		{
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;	
		}

		if (circleId != null) {
			try {
				User user = null;

				ForumTopic forumTopic = new ForumTopic();
				forumTopic.setStatus(1);
				forumTopic.setCircleId(circleId);
				PageBean<ForumTopic> pageBean = new PageBean<ForumTopic>();
				/*
				 * pageBean.setSortFields("status"); pageBean.setOrder("ASC");
				 */
				pageBean.setPage(page);
				pageBean.setParameter(forumTopic);

				pageBean = forumTopicService
						.findForumTopicByConditions(pageBean);
				List<ForumTopic> forumTopicList = pageBean.getResult();

				// List<ForumTopic> forumTopicList =
				// forumTopicService.findForumTopicByCircleId(circleId);
				List<TopicDTO> topicList = new ArrayList<TopicDTO>();
				Map<String, Object> data = new HashMap<String, Object>(5);
				if (forumTopicList != null && forumTopicList.size() > 0) {
					for (ForumTopic tp : forumTopicList) {
						TopicDTO topic = new TopicDTO();

						topic.setCareaterTime(tp.getCreateTime().toString());
						topic.setContent(tp.getContent());
						if (tp.getUserId() != null) {
							topic.setCreaterId(Long.parseLong(tp.getUserId()
									.toString()));
							user = userService.selectByUserId(tp.getUserId());
						}
						if (user != null) {
							topic.setCareaterLevel(user.getvLevel().toString());
							topic.setCreaterImgUrl(user.getPhone());
							topic.setCreaterName(user.getLoginName());
						}

						List<ForumImage> forumImgList = forumImageService
								.findForumImageByTopicId(tp.getTopicId());

						List<ImageDTO> imgList = new ArrayList<ImageDTO>();
						ImageDTO img = null;
						for (ForumImage formImage : forumImgList) {
							img = new ImageDTO();
							img.setImgUrl(formImage.getUrl());
							imgList.add(img);
						}
						topic.setImgList(imgList);
						topic.setIsRecommend(Boolean.parseBoolean(tp
								.getIsRecommend() == 1 ? "true" : "false"));

						/*
						 * topic.setLatestReplierName(latestReplierName);
						 * topic.setLatestReplyTime(latestReplyTime);
						 * topic.setReplyCount(replyCount);
						 */
						topic.setTitle(tp.getTitle());
						topic.setTopicId(Long.parseLong(tp.getTopicId()
								.toString()));
						topic.setVisitCount(100);
						topicList.add(topic);
					}
				}
				else
				{
					response.getResult().setResult("0");
					response.getResult().setMessage("帖子列表为空");
					return response;					
				}
				data.put("topicList", topicList);
				response.setData(data);
			} catch (Exception e) {
				logger.error("getTopicListByCommunityId error", e);
				response.getResult().setResult("0");
				response.getResult().setMessage("获取帖子列表错误");
				return response;
			}
		}
		
		msg = "获取帖子列表成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}

	/**
	 * 获取帖子详情
	 * 
	 * @param getTopicDetailRequest
	 * @return
	 */
	@ServiceMethod(method = "forum.getTopicDetail", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.GET)
	public Response getTopicDetail(GetTopicDetailRequest getTopicDetailRequest) {
		Response response = new Response();
		String msg = "";
		Integer topicId = getTopicDetailRequest.getTopicId();
		User user = null;
		try {			
			ForumTopic tp = new ForumTopic();
			if (topicId != null)
				tp = forumTopicService.findForumTopicById(topicId);
			else
			{
				response.getResult().setResult("0");
				response.getResult().setMessage("参数不合法");
				return response;				
			}

			Map<String, Object> data = new HashMap<String, Object>(5);

			TopicDTO topic = new TopicDTO();
			topic.setCareaterTime(tp.getCreateTime().toString());
			topic.setContent(tp.getContent());
			if (tp.getUserId() != null) {
				topic.setCreaterId(Long.parseLong(tp.getUserId().toString()));
				user = userService.selectByUserId(tp.getUserId());
			}
			if (user != null) {
				topic.setCareaterLevel(user.getvLevel().toString());
				topic.setCreaterImgUrl(user.getHeadUrl());
				topic.setCreaterName(user.getLoginName());
			}

			List<ForumImage> forumImgList = forumImageService
					.findForumImageByTopicId(tp.getTopicId());

			List<ImageDTO> imgList = new ArrayList<ImageDTO>();
			ImageDTO img = null;
			for (ForumImage formImage : forumImgList) {
				img = new ImageDTO();
				img.setImgUrl(formImage.getUrl());
				imgList.add(img);
			}
			topic.setImgList(imgList);
			topic.setIsRecommend(Boolean.parseBoolean(tp.getIsRecommend() == 1 ? "true"
					: "false"));

			/*
			 * topic.setLatestReplierName(latestReplierName);
			 * topic.setLatestReplyTime(latestReplyTime);
			 * topic.setReplyCount(replyCount);
			 */
			topic.setTitle(tp.getTitle());
			topic.setTopicId(Long.parseLong(tp.getTopicId().toString()));
			topic.setVisitCount(100);

			/*
			 * List<ForumReply> forumReplyList = forumReplyService
			 * .findForumReplyByTopicId(topicId);
			 */
			PageBean<ForumReply> pageBean = new PageBean<ForumReply>();
			ForumReply forumReply = new ForumReply();
			forumReply.setStatus(1);
			pageBean.setSortFields("create_time");
			pageBean.setOrder("ASC");
			pageBean.setParameter(forumReply);

			pageBean = forumReplyService.findForumReplyByConditions(pageBean);
			List<ForumReply> forumReplyList = pageBean.getResult();

			List<ReplyDTO> replyList = new ArrayList<ReplyDTO>();
			if (forumReplyList != null && forumReplyList.size() > 0) {
				int i = 0;
				for (ForumReply re : forumReplyList) {
					if (re.getType() == 1) {
					    user=userService.selectByUserId(re.getUserId());
					    if(user==null)
					    	continue;
					    
						if (i == 0) {
							topic.setLatestReplierName(user.getLoginName());
							topic.setLatestReplyTime(re.getCreateTime()
									.toString());
						}

						i++;
						ReplyDTO reply = new ReplyDTO();
						reply.setApproveCount(re.getReward());
						reply.setContent(re.getContent());
						reply.setReplierImgUrl(user.getHeadUrl());
						reply.setReplierName(user.getLoginName());
						reply.setReplyTime(re.getCreateTime().toString());
						reply.setTopicId(topicId);
						reply.setReplierId(re.getReplyId());
						reply.setFloor(i);
						reply.setLevel(1);
						replyList.add(reply);
					}
				}
				topic.setReplyCount(i);
			}

			List<UserDTO> userList = new ArrayList<UserDTO>();
			UserDTO userDTO = null;
			if (forumReplyList != null && forumReplyList.size() > 0) {
				int i = 0;
				for (ForumReply re : forumReplyList) {
					if (re.getType() == 2) {
						userDTO = new UserDTO();
						user = userService.selectByUserId(re.getUserId());

						userDTO.setUserId(Long.parseLong(user.getcUserId()
								.toString()));
						userDTO.setLoginName(user.getLoginName());
						userDTO.setUserImgUrl(user.getHeadUrl());
						userDTO.setvLevel(user.getvLevel());
						userList.add(userDTO);
					}
				}
			}

			data.put("topic", topic);
			data.put("replyList", replyList);
			data.put("rewarderList", userList);

			response.setData(data);

		} catch (Exception e) {
			logger.error("getTopicDetail error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("获取帖子详情错误");
			return response;
		}
		msg = "获取帖子详情成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}
	
	/**
	 * 打赏
	 * @param rewardTopicRequest
	 * @return
	 */
	@ServiceMethod(method = "forum.rewardTopic", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.POST)
	public Response rewardTopic(RewardTopicRequest rewardTopicRequest) {
		Response response = new Response();
		String msg = "";

	    Long userId=rewardTopicRequest.getUserId();
	    Integer topicId=rewardTopicRequest.getTopicId();
	    Integer amount=rewardTopicRequest.getAmount();
	    
	    if(userId==null||StringUtils.isBlank(userId.toString())||topicId==null||StringUtils.isBlank(topicId.toString())||amount==null)
	    {
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;
	    }

		try {
			ForumReply forumReply = new ForumReply();

			forumReply.setReward(amount);
			forumReply.setTopicId(topicId);
			forumReply.setUserId(Integer.parseInt(userId.toString()));
			forumReply.setCreateTime(new Date());
			forumReply.setStatus(1);
			forumReply.setType(2);//打赏
			forumReplyService.saveForumReply(forumReply);

		} catch (Exception e) {
			logger.error("rewardTopic error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("打赏错误");
			return response;
		}
		
		msg = "打赏成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}


	/**
	 * 回帖
	 * @param postReplyRequest
	 * @return
	 */
	@ServiceMethod(method = "forum.postReply", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.POST)
	public Response postReply(PostReplyRequest postReplyRequest) {
		Response response = new Response();
		String msg = "";

	    Long userId=postReplyRequest.getUserId();
	    Integer topicId=postReplyRequest.getTopicId();
	    String content=postReplyRequest.getContent();
	    
	    if(userId==null||StringUtils.isBlank(userId.toString())||topicId==null||StringUtils.isBlank(topicId.toString())||content==null)
	    {
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;
	    }

		try {
			ForumReply forumReply = new ForumReply();

			forumReply.setContent(content);
			forumReply.setTopicId(topicId);
			forumReply.setUserId(Integer.parseInt(userId.toString()));
			forumReply.setCreateTime(new Date());
			forumReply.setStatus(1);
			forumReply.setType(1);
			forumReplyService.saveForumReply(forumReply);

			Map<String, Object> data = new HashMap<String, Object>(5);

			List<ForumReply> forumReplyList = forumReplyService
					.findForumReplyByTopicId(postReplyRequest.getTopicId());

			List<ReplyDTO> replyList = new ArrayList<ReplyDTO>();
			if (forumReplyList != null && forumReplyList.size() > 0) {
				int i = 0;
				for (ForumReply re : forumReplyList) {
					if (re.getType() == 1) {
						i++;
						ReplyDTO reply = new ReplyDTO();
						reply.setApproveCount(re.getReward());
						reply.setContent(re.getContent());
						reply.setFloor(i);
						reply.setLevel(1);
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");// 设置日期格式
						reply.setReplyTime(df.format(new Date()));
						replyList.add(reply);
					}
				}
			}

			data.put("replyList", replyList);
			response.setData(data);

		} catch (Exception e) {
			logger.error("postReply error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("回帖错误");
			return response;
		}
		
		msg = "回帖成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}
}
